//
//  TurnOutView.m
//  SP2P
//
//  Created by 吴建东 on 16/6/12.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "TurnOutView.h"

@interface TurnOutView ()<UITextFieldDelegate,HTTPClientDelegate,UIAlertViewDelegate> {
    
}
@property (nonatomic, strong) NetWorkClient *requestClient;
@property (nonatomic, assign) NSInteger     requestType;
@property (nonatomic, assign) BOOL          isLoading;
@end

@implementation TurnOutView


- (void)loadView {
    _scrollView.frame = RECTMAKE(0, 0, self.frame.size.width, self.frame.size.height);
    [self initView];
}

- (void)reloadTradePwdStaus {
    _passwordTextField.delegate = self;
    if (AppDelegateInstance.userInfo.isPayPasswordStatus) {
        _passwordTextField.placeholder = @"请输入交易密码";
        _passwordTextField.userInteractionEnabled = YES;
        _passwordTextField.secureTextEntry = YES;
        _passwordTextField.textAlignment = NSTextAlignmentRight;
    }else {
        _passwordTextField.placeholder = @"点击设置交易密码";
        _passwordTextField.secureTextEntry = NO;
        _passwordTextField.userInteractionEnabled = YES;
        _passwordTextField.textAlignment = NSTextAlignmentCenter;
    }
}

- (void)setBalanceStr:(NSString *)balanceStr {
    _balanceStr = balanceStr;
    
    _detailLabel.text = _balanceStr;
}

- (void)setSqbBalance:(double)sqbBalance {
   _sqbBalance = sqbBalance;
    
    NSString *sqbBalanceStr = [NSString stringWithFormat:@"%@",[CommonClass formatConversion:_sqbBalance type:0]];
    _avallableBalanceLabel.text = [NSString stringWithFormat:@"%@ 元",sqbBalanceStr];
    
    NSString *sqbFreezeBalanceStr = [NSString stringWithFormat:@"%@",[CommonClass formatConversion:_sqbBalance - _sqbFreezeBalance type:0]];
    _amountTextField.placeholder = [NSString stringWithFormat:@"本次可转出%@",sqbFreezeBalanceStr];
}

- (void)setUserBanksDict:(NSDictionary *)userBanksDict {
    _userBanksDict = userBanksDict;
    
    if (_userBanksDict) {
        NSString *bankNameStr = [NSString stringWithFormat:@"%@",_userBanksDict[@"bankName"]];
        bankNameStr = [CommonClass setBankLogoImageWithBankName:bankNameStr imageView:_logoImageView];
        _nameLabel.text = bankNameStr;
        NSString *bankNumStr = [NSString stringWithFormat:@"%@",_userBanksDict[@"account"]];
        _detailLabel.text = [NSString stringWithFormat:@"尾号%@",[bankNumStr substringFromIndex:bankNumStr.length-4]];
    }else {
        
    }
    
}

- (IBAction)turnOutButtonClick:(id)sender {
    if (self.viewType == 1) {
        if (_userBanksDict == nil) {
            [SVProgressHUD showErrorWithStatus:@"您尚未完成实名认证信息"];
            return;
        }
    }
    
    if (_amountTextField.text.doubleValue <= 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的金额"];
        return;
    }
    if (_viewType == 1) {
        if (_amountTextField.text.doubleValue < 100) {
            [SVProgressHUD showErrorWithStatus:@"最低转出金额不能小于100元"];
            return;
        }
    }
    
    if (!AppDelegateInstance.userInfo.isPayPasswordStatus) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您尚未设置交易密码" message:@"是否前去设置交易密码？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 8;
        [alert show];
        return;
    }
    if (_passwordTextField.text.length <= 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入交易密码"];
        return;
    }
    
    [self turnOutRequest];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag==8 && buttonIndex==1) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(gotoSetTradePassword)]) {
            [self.delegate gotoSetTradePassword];
        }
    }
}

- (void)textFieldValueChanged {
    if (_amountTextField.text.doubleValue>0 && _passwordTextField.text.length>0) {
        [CommonClass buttonEnableWithButton:_turnOutButton enable:YES];
    }else {
        [CommonClass buttonEnableWithButton:_turnOutButton enable:NO];
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == _passwordTextField) {
        if (!AppDelegateInstance.userInfo.isPayPasswordStatus) {
            if (self.delegate && [self.delegate respondsToSelector:@selector(gotoSetTradePassword)]) {
                
                [self keyBoardHidden];
                [self.delegate gotoSetTradePassword];
            }
            return NO;
        }
    }
    
    return YES;
}

- (void)keyBoardHidden {
    [_amountTextField resignFirstResponder];
    [_passwordTextField resignFirstResponder];
}

#pragma mark - Data
- (void)turnOutRequest {
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求,请稍候..."];
        return;
    }
    
    _requestType = 1;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    if (self.viewType == 1) {
        [parameters setObject:@"521" forKey:@"OPT"];
        [parameters setObject:@"" forKey:@"body"];
        [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
        [parameters setObject:_amountTextField.text forKey:@"amount"];
        [parameters setObject:[NSString stringWithFormat:@"%@",[_userBanksDict objectForKey:@"id"]] forKey:@"bankId"];
        [parameters setObject:@"2" forKey:@"type"];
        [parameters setObject:[NSString encrypt3DES:_passwordTextField.text key:DESkey] forKey:@"payPassword"];
        
        
    }else {
        [parameters setObject:@"505" forKey:@"OPT"];
        [parameters setObject:@"" forKey:@"body"];
        [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"userId"];
        NSString *password = [NSString encrypt3DES:_passwordTextField.text key:DESkey];
        [parameters setObject:password forKey:@"dealpwd"];
        [parameters setObject:[NSString stringWithFormat:@"%@",_amountTextField.text] forKey:@"money"];
    }
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

- (void)startRequest {
    _isLoading = YES;
}

- (void)httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    _isLoading = NO;
    NSDictionary *dics=(NSDictionary *)obj;
    DLOG(@"--%@",dics);
    NSString *errorStr=[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]];
    if ([errorStr isEqualToString:@"-1"]) {
        [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%@",[dics objectForKey:@"msg"]]];
        if (self.delegate && [self.delegate respondsToSelector:@selector(turnOutSuccess)]) {
            [self.delegate turnOutSuccess];
        }
        
    }else {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[dics objectForKey:@"msg"]]];
    }
}

- (void)httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    _isLoading = NO;
}

- (void) networkError {
    _isLoading = NO;
}

#pragma mark - View
- (void)initView {
    _nameLabel.font = KFontSize(13);
    _detailLabel.font = KFontSize(13);
    _amountValue.font = KFontSize(14);
    _avallableBalanceLabel.font = KFontSize(14);
    _avallableBalanceValue.font = KFontSize(14);
    _transAmountValue.font = KFontSize(14);
    _amountTextField.font = KFontSize(14);
    _moneyTypeValue.font = KFontSize(14);
    _passwordValue.font = KFontSize(14);
    _passwordTextField.font = KFontSize(14);
    _turnOutButton.titleLabel.font = KFontSize(15);
    _remindLabel.font = KFontSize(14);
    
    if (self.viewType == 1) {
        _nameLabel.text = [NSString stringWithFormat:@"工商银行"];
        _detailLabel.text = [NSString stringWithFormat:@"尾号%@",@"0000"];
    }else {
        _nameLabel.text = [NSString stringWithFormat:@"账户余额"];
        _detailLabel.text = [NSString stringWithFormat:@"0.00元"];
    }
    
    _passwordTextField.delegate = self;
    [self reloadTradePwdStaus];
    
    NSString *mindStr = [NSString stringWithFormat:@"%@",@"*转账提示：\n1.转入和转出均免手续费。\n\n2.转出最快1分钟到账，部分银行将在2小时内到账。如遇到银行系统升级，请关注网站公告，耐心等待。单日累计5万元内(包含5万)T+0日到账，5万以上T+2日到账。\n\n3.为防止快进快出，用户资金转入后，均需满足最少24小时。\n\n4.严禁非法套现行为，一经发现将终止该账户的使用！"];
    CGFloat mindHeight = [MyTools getSizeOfString:mindStr maxWidth:MSWIDTH - 20 maxHeight:1000 withFontSize:14].height;
    CGRect frame = _remindLabel.frame;
    frame.size.height = mindHeight;
    _remindLabel.frame = frame;
    _remindLabel.attributedText = [MyTools getNSMutableAttributedStringWithText:mindStr start:0 end:1 textColor:KColor textFont:KFontSize(14)];
    
    _scrollView.contentSize = CGSizeMake(0, GetMaxY(_remindLabel) + 50);
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValueChanged) name:UITextFieldTextDidChangeNotification object:_amountTextField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValueChanged) name:UITextFieldTextDidChangeNotification object:_passwordTextField];
}

- (void)layoutSubviews {
    CGRect frame = _remindLabel.frame;
    frame.origin.y = GetMaxY(_turnOutButton) + KAdaptNum(16);;
    _remindLabel.frame = frame;
    
    _scrollView.contentSize = CGSizeMake(0, GetMaxY(_remindLabel) + 50);
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
